
const Toast = require('../pages/MyPackage/components/Toast');

// 重复调用一个 promise 至其 resolve，则返回一个 Promise.resolve
// 到达指定次数后返回 Promise.reject
function tryAtMost(retryInterval, maxRetries, fn, param, resolve, reject) {
    // 传入函数和参数，每次创建新 promise
    const promise = fn(param)
    function repeat(resolve, reject) {
        promise.then(res => {
            //成功返回
            resolve(res)
        }).catch(err => {
            if (maxRetries > 0) {
                //重复调用
                console.log(`try func: ${fn.name}, maxRetries: ${maxRetries}`)
                setTimeout(() => {
                    tryAtMost(retryInterval, maxRetries - 1, fn, param, resolve, reject)
                }, retryInterval)
            } else {
                //失败返回
                reject(err)
            }
        })
    }
    if (resolve) {
        repeat(resolve, reject)
    } else {
        return new Promise((resolve, reject) => {
            repeat(resolve, reject)
        })
    }
}

function formatPhone(phone) { // 校验手机号，转换成*** **** ****
    return `${phone.substring(0, 3)} ${phone.substring(3, 7)} ${phone.substring(7, 11)}`;
}

export default {
    tryAtMost,
    getParams() {
        let url = window.location.href;
        let urlJson = {};
        if (url.indexOf('?') != -1) {
            let arr2 = url.split('?')[1].split('#')[0].split('&');
            for (let i in arr2) {
                let str = arr2[i];
                let index = str.indexOf('=');
                let key = str.substring(0, index);
                let value = str.substring(index + 1);
                urlJson[key] = value;
            }
        }
        return urlJson;
    },
    createCookie(name, value, time, expire_time) {
        var expires = "";
        if (time) {
            var date = new Date();
            date.setTime(time * 1000 + expire_time * 1000);
            expires = "; expires=" + date.toGMTString();
            //expires = "; expires=" + date;
        }
        document.cookie = name + "=" + value + expires + "; path=/";

    },
    readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');

        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    },
    eraseCookie(name) {
        this.createCookie(name, "", Date.now() / 1000, - 1);
    },
    queryString(url) {
        let obj = {}
        try {
            url.split('?')[1].split('&').forEach(d => {
                const k = d.split('=')[0]
                const v = d.split('=')[1]
                Object.assign(obj, {
                    [k]: v
                })
            })
        } catch (error) {
        }
        return obj
    },
    isValidQRCode(str = '') {
        return str.indexOf('cabinet_code') > -1
    },
    formatPhone,
    copyExpCode(value, type = 'input') {
        const input = document.createElement(type);
        input.setAttribute('readonly', 'readonly'); // 设置为只读, 防止在 ios 下拉起键盘
        // input.setAttribute('value', value); // textarea 不能用此方式赋值, 否则无法复制内容
        input.value = value;
        document.body.appendChild(input);
        input.setSelectionRange(0, 9999); // 防止 ios 下没有全选内容而无法复制
        input.select();
        document.execCommand('copy');
        document.body.removeChild(input);
        Toast.success({ content: '已复制到粘贴板' });
    },
    getDate() {
        const date = new Date((new Date().getTime() - 90 * 24 * 60 * 60 * 1000));
        const y = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const MM = month < 10 ? ('0' + month) : month;
        const DD = day < 10 ? ('0' + day) : day;

        return y + '-' + MM + '-' + DD + ' ' + '00:00:00';
    }
}